<template>
  <div class="app-container">
    <vxe-toolbar ref="xToolbar" export custom>
      <template #buttons>
        <vxe-button @click="insertEvent">新增</vxe-button>
        <vxe-button @click="saveEvent">保存</vxe-button>
      </template>
    </vxe-toolbar>

    <vxe-table
      show-overflow
      keep-source
      border="inner"
      ref="xTree"
      :row-config="{ keyField: 'id' }"
      :column-config="{ resizable: true }"
      :tree-config="treeConfig"
      :loading="xTreeOpt.loading"
      :data="xTreeOpt.tableData"
      :edit-config="{ trigger: 'click', mode: 'row', showStatus: true, beforeEditMethod: beforeEditMethod }"
      :export-config="{}"
      :checkbox-config="{ labelField: 'id' }"
      @toggle-tree-expand="toggleExpandChangeEvent"
      @edit-closed="editClosedEvent"
    >
      <vxe-column type="checkbox" width="60" tree-node />
      <!-- <vxe-column field="id" title="ID" tree-node /> -->
      <vxe-column field="departCode" title="部门编码" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.departCode" type="text" />
        </template>
      </vxe-column>
      <vxe-column field="departName" title="部门名称" :edit-render="{}">
        <template #edit="{ row }">
          <vxe-input v-model="row.departName" type="text" />
        </template>
      </vxe-column>
      <vxe-column field="manager" title="负责人">
        <!-- <template #edit="{ row }">
        <vxe-input v-model="row.type" type="text"></vxe-input>
      </template> -->
      </vxe-column>
      <vxe-column field="createUser" title="创建人" />
      <vxe-column field="createTime" title="创建时间" />
      <vxe-column title="操作" width="300">
        <template #default="{ row }">
          <vxe-button type="text" status="primary" @click="insertRow(row, 'current')">新增部门</vxe-button>
          <!-- <vxe-button type="text" status="primary" @click="insertRow(row, 'top')">新增子部门</vxe-button> -->
          <vxe-button type="text" status="primary" @click="insertRow(row, 'bottom')">新增子部门</vxe-button>
          <vxe-button type="text" status="primary" @click="removeRow(row)">删除节点</vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, Ref, nextTick } from "vue"
import { VXETable, VxeTableEvents, VxeTableInstance, VxeTablePropTypes, VxeToolbarInstance } from "vxe-table"
import {
  getDepartmentListApi,
  batchCreateDepartmentApi,
  deleteDepartmentApi,
  updateDepartmentApi,
  IDeparment
  // ISearchDepartmentReq,
  // IDeparment
} from "@/api/department"
import { type ElMessageBoxOptions, ElMessageBox, ElMessage } from "element-plus"
const xTree = ref<VxeTableInstance>(null)
const xToolbar = ref<VxeToolbarInstance>()
const treeConfig: Ref<VxeTablePropTypes.TreeConfig> = ref({
  transform: true,
  rowField: "id",
  parentField: "parentId"
})
const xTreeOpt = reactive({
  loading: false,
  tableData: []
})

const findDepartmentList = () => {
  xTreeOpt.loading = true
  getDepartmentListApi({})
    .then((res) => {
      xTreeOpt.tableData = res.data
      xTreeOpt.loading = false
    })
    .catch(() => {
      xTreeOpt.loading = false
    })
}
const searchMethod = () => {
  const $table = xTree.value
  // 清除所有状态
  $table.clearAll()
  return findDepartmentList()
}
const insertRow = async (currRow: any, locat: string) => {
  const $table = xTree.value
  const date = new Date()
  // 如果 null 则插入到目标节点顶部
  // 如果 -1 则插入到目标节点底部
  // 如果 row 则有插入到效的目标节点该行的位置
  if (locat === "current") {
    const record = {
      departName: "",
      parentId: currRow.parentId
    }
    const { row: newRow } = await $table.insertAt(record, currRow)
    await $table.setEditRow(newRow) // 插入子节点
  } else if (locat === "top") {
    const record = {
      departName: "",
      parentId: currRow.id
    }
    const { row: newRow } = await $table.insert(record)
    await $table.setTreeExpand(currRow, true) // 将父节点展开
    await $table.setEditRow(newRow) // 插入子节点
  } else if (locat === "bottom") {
    const record = {
      departName: "",
      parentId: currRow.id
    }
    const { row: newRow } = await $table.insertAt(record, -1)
    await $table.setTreeExpand(currRow, true) // 将父节点展开
    await $table.setEditRow(newRow) // 插入子节点
  }
}

const saveEvent = () => {
  const $table = xTree.value
  const { insertRecords, updateRecords } = $table.getRecordset()
  if (insertRecords.length > 0) {
    batchCreateDepartmentApi(insertRecords).then(() => {
      searchMethod()
    })
  }
  // if( removeRecords.length > 0 ){

  // }
  // VXETable.modal.alert(
  //   `insertRecords=${insertRecords.length} removeRecords=${removeRecords.length} updateRecords=${updateRecords.length}`
  // )
}

const editClosedEvent: VxeTableEvents.EditClosed = ({ row, column }) => {
  const $table = xTree.value
  const field = column.field
  const cellValue = row[field]
  // 判断单元格值是否被修改
  if (field !== "departCode" && $table.isUpdateByRow(row, field)) {
    const data: IDeparment = Object.assign({}, row)
    data.departCode = undefined
    updateDepartmentApi(row).then(() => {
      VXETable.modal.message({
        content: `局部保存成功！ ${field}=${cellValue}`,
        status: "success"
      })
      $table.reloadRow(row, null, field)
    })
  } else {
    $table.reloadRow(row, null, field)
  }
}

const removeRow = (row: any) => {
  if (row && row.id) {
    deleteDepartmentApi({ id: row.id, recursive: 0 }).then(() => {
      searchMethod()
    })
  } else {
    const $table = xTree.value
    $table.remove(row)
  }
}

const beforeEditMethod = ({ row, column }) => {
  if (row && row.id) {
    return !(column.field === "departCode")
  }
  return true
}

const insertEvent = async () => {
  const $table = xTree.value
  const date = new Date()
  const record = {
    name: "新数据",
    id: Date.now(),
    parentId: null,
    date: `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`
  }
  const { row: newRow } = await $table.insert(record)
  await $table.setEditRow(newRow)
}
onMounted(() => {
  // 将表格和工具栏进行关联
  const $xTree = xTree.value
  const $toolbar = xToolbar.value
  $xTree.connect($toolbar)
  searchMethod()
})

// const demo1 = reactive({
//   tableData: [
//   ]
// })

const toggleExpandChangeEvent = (params: any) => {
  const $table = xTree.value
  const { row, expanded } = params
  console.log("节点展开事件", expanded, "获取父节点：", $table.getParentRow(row))
}
</script>
